package com.town.garden.strategy.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.town.garden.component.RedisRepository;
import com.town.garden.constant.GlobalConstant;
import com.town.garden.entiy.AlarmList;
import com.town.garden.entiy.AlertEvent;
import com.town.garden.entiy.FaceAlarm;
import com.town.garden.enums.AlertEventEnum;
import com.town.garden.storage.NvrSessionStorage;
import com.town.garden.strategy.ProcessAlarmEventStrategy;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @Description 目标告警处理策略实现类
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/5/13
 */
@Component
@AllArgsConstructor
@Slf4j
public class ProcessFaceAlarmEventStrategyImpl implements ProcessAlarmEventStrategy {
    private final RedisRepository redisRepository;

    @Override
    public boolean isMatch(List<AlarmList> alarmList) {
        if (CollectionUtil.isNotEmpty(alarmList)) {
            for (AlarmList alarmList1 : alarmList
            ) {
                if (CollectionUtil.isNotEmpty(alarmList1.getFaceAlarm())) {
                    return true;
                }
            }
        } else {
            return false;
        }
        return false;
    }

    @Override
    public void doProcessAlarmEvent(List<AlarmList> alarmLists) {
        for (AlarmList alarmList1:alarmLists
             ) {
            if (Objects.nonNull(alarmList1)&&CollectionUtil.isNotEmpty(alarmList1.getFaceAlarm())){
                for (FaceAlarm faceAlarm : alarmList1.getFaceAlarm()
                ) {
                    //抓拍目标图片
                    final String snapFaceImg = faceAlarm.getSnapFaceImg();
                    //组id  2 白名单 3 黑名单 4 陌生人
                    final Long grpId = faceAlarm.getGrpId();
                    //转换告警时间
                    DateTime dateTime = DateUtil.parse(alarmList1.getTime(), GlobalConstant.NVR_ALARM_TIME_FORMAT);
                    String time = DateUtil.format(dateTime, DatePattern.NORM_DATETIME_PATTERN);
                    //封装统一事件对象 放入redis队列中
                    AlertEvent alertEvent = new AlertEvent(GlobalConstant.CHANNEL_PREFIX_NAME + faceAlarm.getSnapChn(),
                            time, AlertEventEnum.getEnumByCode(faceAlarm.getAlarmFlags()),
                            NvrSessionStorage.CHANNEL_IP_MAP.get(GlobalConstant.CHANNEL_PREFIX_NAME + faceAlarm.getSnapChn())
                    );
                    log.info("execute do process FaceAlarmEvent");
                    redisRepository.leftPush(GlobalConstant.ALARM_EVENT_KEY, alertEvent);
                }
            }
        }
    }
}
